<template>
  <view class="container">
    <view class="title">QNBle Demo</view>

    <button @click="checkPermission">检查蓝牙权限</button>
    <button @click="startScan">开始扫描设备</button>
    <button @click="stopAll">停止扫描/断开设备</button>

    <view class="device-list">
      <view v-for="item in devices" :key="item.deviceId" class="device-item">
        <text>{{ item.name || '未知设备' }} (RSSI: {{ item.rssi }})</text>
        <button size="mini" @click="connectDevice(item)">连接</button>
      </view>
    </view>

    <view class="measure-data" v-if="scaleData">
      <view class="subtitle">最新测量数据</view>
      <text>体重: {{ scaleData.weight }} kg</text>
      <text>体脂率: {{ scaleData.bodyfat }} %</text>
      <text>BMI: {{ scaleData.bmi }}</text>
      <text>水分: {{ scaleData.water }} %</text>
      <text>肌肉率: {{ scaleData.muscle }} %</text>
    </view>

    <view class="log">
      <text v-for="(line, idx) in logs" :key="idx">{{ line }}</text>
    </view>
  </view>
</template>

<script>
// ⚠️ 注意导入方式
import * as QNBleSDK from '@/utils/qnble_uni-app.js'

const QNBle = QNBleSDK.default || QNBleSDK
const { checkBlePermission } = QNBleSDK

export default {
  data() {
    return {
      qnBle: null,
      devices: [],
      logs: [],
      scaleData: null // 最新体脂秤数据
    }
  },
  onLoad() {
    this.qnBle = new QNBle()

    this.qnBle.setBleEventListener({
      onBluetoothEnableChange: (e) => {
        this.addLog('蓝牙开关变化: ' + JSON.stringify(e))
      },
      onStartDiscoveryDevice: () => {
        this.addLog('开始扫描设备')
      },
      onStopDiscoveryDevice: () => {
        this.addLog('停止扫描设备')
      },
      onBleDeviceFound: (device) => {
        this.addLog('发现设备: ' + JSON.stringify(device))
        if (!this.devices.find(d => d.deviceId === device.deviceId)) {
          this.devices.push(device)
        }
      },
      onConnected: ({ deviceId }) => {
        this.addLog('已连接: ' + deviceId)
      },
      onDisconnected: ({ deviceId }) => {
        this.addLog('已断开: ' + deviceId)
      },
      onGetScaleData: (data) => {
        this.addLog('收到测量数据: ' + JSON.stringify(data))
        this.scaleData = {
          weight: data.weight,
          bodyfat: data.bodyfat,
          bmi: data.bmi,
          water: data.water,
          muscle: data.muscle
        }
      }
    })
  },
  methods: {
    addLog(msg) {
      console.log(msg)
      this.logs.unshift(new Date().toLocaleTimeString() + ' ' + msg)
    },

    async checkPermission() {
      try {
        await checkBlePermission()
        this.addLog('蓝牙权限正常')
      } catch (e) {
        console.error('蓝牙权限错误对象:', e)
        const code = e.code || ''
        const desc = e.desc || ''
        const message = e.message || ''
        this.addLog(`蓝牙权限错误: code=${code}, desc=${desc}, message=${message}`)
      }
    },

    async startScan() {
      try {
        await this.qnBle.init(wx)
        await this.qnBle.startBleDeviceDiscovery()
        this.devices = []
      } catch (err) {
        this.addLog('启动扫描失败: ' + JSON.stringify(err))
      }
    },

    async connectDevice(device) {
      try {
        await this.qnBle.createBleConnection(device)
        this.addLog('连接成功: ' + device.deviceId)
      } catch (err) {
        this.addLog('连接失败: ' + JSON.stringify(err))
      }
    },

    async stopAll() {
      try {
        await this.qnBle.stop()
        this.addLog('已停止扫描并断开所有设备')
      } catch (err) {
        this.addLog('stop 错误: ' + JSON.stringify(err))
      }
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}
.subtitle {
  font-size: 28rpx;
  font-weight: bold;
  margin-top: 20rpx;
  margin-bottom: 10rpx;
}
.device-list {
  margin-top: 20rpx;
}
.device-item {
  margin: 10rpx 0;
  padding: 10rpx;
  border: 1px solid #ccc;
  border-radius: 8rpx;
}
.measure-data {
  margin-top: 30rpx;
  padding: 20rpx;
  border: 1px solid #0081ff;
  border-radius: 10rpx;
  background: #f0f8ff;
}
.measure-data text {
  display: block;
  margin: 5rpx 0;
}
.log {
  margin-top: 30rpx;
  font-size: 24rpx;
  color: #666;
  white-space: pre-wrap;
}
</style>
